package znbkBkfx.BKFX_ZW;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseFragment;
import com.example.znbk.znbklibrary.widget.CustomEditText;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.google.gson.Gson;
import com.lancoo.znbkxx.R;
import com.lancoo.znbkxx.beans.UserInfoBean;
import com.lancoo.znbkxx.net.URLConstant;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import znbkBkfx.AboutRecordPlay.AudioPlayerView;
import znbkBkfx.BKFX_ZW.aboutPhotosPicker.FullyGridLayoutManager;
import znbkBkfx.BKFX_ZW.aboutPhotosPicker.PhotoPickerAdapter;
import znbkBkfx.BKFX_ZW.aboutPhotosPicker.SelectDialog;
import znbkBkfx.BkfxActivity;
import znbkBkfx.GetBkfxJson.BkfxPaperEntity;
import znbkBkfx.PostSaveSubjectiveQues.PostSaveSubjectiveItemQuesAnswer_interface;
import znbkBkfx.PostSaveSubjectiveQues.ResultSubjectiveItemJson;
import znbkBkfx.PostSaveSubjectiveQues.SubjectiveItemAnswerModel;

@SuppressLint("ValidFragment")
public class BkfxZwFragment extends BaseFragment {

    private int answerViewFlag  = 0;//0：输入作答 1：语音作答 2：照片作答
    private BkfxPaperEntity bkfxPaperEntity;
    private int childIndex = -1;
    private CallBackFragmentZw callBackFragmentZw;
    public BkfxZwFragment(int answerViewFlag,BkfxPaperEntity bkfxPaperEntity, int childIndex, CallBackFragmentZw callBackFragmentZw){
        this.answerViewFlag = answerViewFlag;
        this.bkfxPaperEntity  =bkfxPaperEntity;
        this.childIndex = childIndex;
        this.callBackFragmentZw = callBackFragmentZw;
    }

    @Override
    protected int createLayout() {
        return R.layout.bkfx_fragment_zw;
    }

    private WebView mWvAsk;
    private RelativeLayout mRlAnswerStypeButton;
    private RelativeLayout mRlAnswerContentView;
    private RelativeLayout mRlAnswerZwResultView;
    private TextView mTvItemAnswer,mTvStuAnswer;
    private AudioPlayerView mApvMyResultRecord;
    private RecyclerView mRvPhotoPickerResult;
    private TextView mTvQuesNumber;
    private ScaleButton mSBtnManualInput,mSBtnSpeechInput,mSBtnPhotosUpload;
    private LinearLayout mLlViewSpeechInput;
    private LinearLayout mLlViewManualInput,mLlViewPhotosUpload;//键盘输入//语音输入//照片上传
//    private ScaleButton mSBtnSubmitManualInput,mSBtnSubmitSpeechInput,mSBtnSubmitPhotosUpload;
    private ScaleButton mSBtnSubmit;
    private ScaleButton mSBtnClearSpeechInput;
    private Button mBtnPressSpeechInput;
    private AudioPlayerView mApvMyRecord;
    private CustomEditText mCEdtManualInput, mCEdtSpeechInput;

    private String ManualInputStuAnswer = "";//手动输入内容
    private String SpeechInputStuAnswer = "";//语音输入内容
    private String SpeechInputAudioPath = "";//语音语音输入音频路径
    private String PhotosUploadImagePath = "";//照片上传相关路径
    @Override
    protected void initView(View view) {

        mWvAsk = view.findViewById(R.id.wv_ask);
        mWvAsk.setBackgroundColor(0); // 设置背景色
        mWvAsk.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        showZwAsk();//显示作文问题题干

        mSBtnSubmit = view.findViewById(R.id.sbtn_submit);
        mSBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(answerViewFlag==0){
                    //提交普通输入答案
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer(ManualInputStuAnswer);
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).setSubmitState(2);

                    //提交手动输入作答内容
                    //隐藏作答输入框，显示参考范例和我的答案
                    mRlAnswerStypeButton.setVisibility(View.GONE);
                    mRlAnswerContentView.setVisibility(View.GONE);
                    mRlAnswerZwResultView.setVisibility(View.VISIBLE);
                    //显示范例和我的答案
                    String ModelEssay = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
                    String MyAnswer = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
                    mTvItemAnswer.setText(Html.fromHtml(ModelEssay));
                    if(MyAnswer.equals("")){
                        MyAnswer = "未作答";
                    }
                    mTvStuAnswer.setText(Html.fromHtml(MyAnswer));
                    //显示范例，显示我的作答
                    mTvItemAnswer.setVisibility(View.VISIBLE);
                    mTvStuAnswer.setVisibility(View.VISIBLE);
                    //隐藏我的录音
                    mApvMyResultRecord.setVisibility(View.GONE);
                    //隐藏照片
                    mRvPhotoPickerResult.setVisibility(View.GONE);

                    //此处需要添加主观题智能评阅提交功能
                    callBackFragmentZw.saveBkfx_ZwQuesAnswer();
                    callBackFragmentZw.pageMoveNext();
                }else if(answerViewFlag==1){
                    //提交语音输入答案
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().get(0).
                            getSubChildList().get(0).getSubChildItem().get(0).setAudioPath(SpeechInputAudioPath);
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer(SpeechInputStuAnswer);
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).setSubmitState(2);

                    //隐藏作答输入框，显示参考范例和我的答案
                    mRlAnswerStypeButton.setVisibility(View.GONE);
                    mRlAnswerContentView.setVisibility(View.GONE);
                    mRlAnswerZwResultView.setVisibility(View.VISIBLE);
                    //显示范例和我的答案
                    String ModelEssay = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
                    String MyAnswer = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
                    mTvItemAnswer.setText(Html.fromHtml(ModelEssay));
                    if(MyAnswer.equals("")){
                        MyAnswer = "未作答";
                    }
                    mTvStuAnswer.setText(Html.fromHtml(MyAnswer));

                    //显示范例，显示我的作答
                    mTvItemAnswer.setVisibility(View.VISIBLE);
                    mTvStuAnswer.setVisibility(View.VISIBLE);
                    //隐藏照片
                    mRvPhotoPickerResult.setVisibility(View.GONE);
                    String AudioPath =  bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().get(0).
                            getSubChildList().get(0).getSubChildItem().get(0).getAudioPath();
                    if(AudioPath.equals("")) {
                        //隐藏我的录音
                        mApvMyResultRecord.setVisibility(View.GONE);
                    }else{
                        //显示我的录音
                        mApvMyResultRecord.setVisibility(View.VISIBLE);
                    }
                }else if(answerViewFlag==2){
                    //提交照片
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().get(0).
                            getSubChildList().get(0).getSubChildItem().get(0).setAudioPath(PhotosUploadImagePath);
                    bkfxPaperEntity.getPaperAnswer().get(childIndex).setSubmitState(2);
                    //隐藏作答输入框，显示参考范例和我的答案
                    mRlAnswerStypeButton.setVisibility(View.GONE);
                    mRlAnswerContentView.setVisibility(View.GONE);
                    mRlAnswerZwResultView.setVisibility(View.VISIBLE);
                    //显示范例和我的答案
                    String ModelEssay = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                            get(0).getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
                    mTvItemAnswer.setText(Html.fromHtml(ModelEssay));

                    //隐藏范例，显示我的作答
                    mTvItemAnswer.setVisibility(View.VISIBLE);
                    mTvStuAnswer.setVisibility(View.GONE);
                    //隐藏我的录音
                    mApvMyResultRecord.setVisibility(View.GONE);
                    //显示照片
                    mRvPhotoPickerResult.setVisibility(View.VISIBLE);
                }
            }
        });

        mRlAnswerStypeButton = view.findViewById(R.id.rl_answerStypeButton);
        mRlAnswerContentView = view.findViewById(R.id.rl_answerContentView);
        mRlAnswerZwResultView = view.findViewById(R.id.rl_answerZwResultView);
        int SubmitState = bkfxPaperEntity.getPaperAnswer().get(childIndex).getSubmitState();
        if(SubmitState==2){
            mRlAnswerStypeButton.setVisibility(View.GONE);
            mRlAnswerContentView.setVisibility(View.GONE);
            mRlAnswerZwResultView.setVisibility(View.VISIBLE);
            mSBtnSubmit.setVisibility(View.GONE);
        }else{
            mRlAnswerStypeButton.setVisibility(View.VISIBLE);
            mRlAnswerContentView.setVisibility(View.VISIBLE);
            mRlAnswerZwResultView.setVisibility(View.GONE);
            mSBtnSubmit.setVisibility(View.VISIBLE);
        }
        mTvItemAnswer = view.findViewById(R.id.tv_itemAnswer);
        mTvStuAnswer = view.findViewById(R.id.tv_stuAnswer);
        mApvMyResultRecord = view.findViewById(R.id.apv_myResultRecord);
        mRvPhotoPickerResult = view.findViewById(R.id.rv_photoPickerResult);

        FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 3,
                GridLayoutManager.VERTICAL, false);
        mRvPhotoPickerResult.setLayoutManager(manager);
        PhotoShowResultAdapter adapter = new PhotoShowResultAdapter(getActivity());
        mRvPhotoPickerResult.setAdapter(adapter);


        if(SubmitState==2){
            String ItemAnswer = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
            String StuAnswer = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
//            mCEdtModelEssay.setText(Html.fromHtml(ModelEssay));
            mTvItemAnswer.setText(Html.fromHtml(ItemAnswer));
            if(StuAnswer.equals("")){
                mTvStuAnswer.setText("未作答");
            }else{
                mTvStuAnswer.setText(StuAnswer);
            }
        }

        mTvQuesNumber = view.findViewById(R.id.tv_quesNumber);
        int SortIndex = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().
                get(0).getSubChildList().get(0).getSubChildItem().get(0).getSortIndex();
        mTvQuesNumber.setText(String.valueOf(SortIndex)+"、写作");


        /*
        * **********************
         *****手动输入相关*****
         **********************
        * */
        mCEdtManualInput = view.findViewById(R.id.cedt_manualInput);
        mCEdtManualInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                ManualInputStuAnswer = s.toString().trim();
            }
        });

        /*
         **********************
         *****语音输入相关*****
         **********************
        * */
        mCEdtSpeechInput = view.findViewById(R.id.cedt_speechInput);
        mCEdtSpeechInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                 SpeechInputStuAnswer = s.toString().trim();
            }
        });
        mSBtnClearSpeechInput = view.findViewById(R.id.sbtn_clearSpeechInput);
        mSBtnClearSpeechInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清空语音输入内容
                mCEdtSpeechInput.setText("");
            }
        });
        mBtnPressSpeechInput = view.findViewById(R.id.btn_recordSpeakInput);
        mBtnPressSpeechInput.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        showRecordPopwindow(mBtnPressSpeechInput);
                        Log.e("mSBtnRecordAnswer", "===============点击了==============");
                        mRecoderUtils = new AudioRecoderUtils();
                        SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                        mRecoderUtils.startRecord();
                        return true;
                    case MotionEvent.ACTION_UP:
                        popWindow.dismiss();
                        mRecoderUtils.stopRecord();
                        SkEgnManager.getInstance(getActivity()).stopRecord();
                        //合成音频
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        popWindow.dismiss();
                        mRecoderUtils.stopRecord();
                        return true;
                }
                return false;
            }
        });
//        mApvMyRecord = view.findViewById(R.id.apv_myRecord);
//        String AudioPath="http://139.9.94.204:10117/lgRs/CBCE07048DHE10000DD/3c6febdba7fa232da2645dea2907a23d.mp3";
//        mApvMyRecord.setUrl(AudioPath);
//
        /*
        **********************
        *****图片输入相关*****
        **********************
        * */
        mSBtnManualInput = view.findViewById(R.id.sbtn_manualInput);
        mSBtnSpeechInput = view.findViewById(R.id.sbtn_speechInput);
        mSBtnPhotosUpload = view.findViewById(R.id.sbtn_photosUpload);
        mSBtnManualInput.setSelected(true);
        mLlViewManualInput = view.findViewById(R.id.ll_viewManualInput);
        mLlViewSpeechInput = view.findViewById(R.id.ll_viewSpeechInput);
        mLlViewPhotosUpload = view.findViewById(R.id.ll_viewPhotosUpload);
        changeZwAnswerType();//设置作文作答方式

        showPhotosUploadView(view);//照片上传作答流程

    }

    /*
    * 显示作文题题干
    * */
    private void showZwAsk(){
        String SubChildAsk = bkfxPaperEntity.getQuesList().get(childIndex).getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
        SubChildAsk =SubChildAsk.replaceAll("—","_");
        SubChildAsk =SubChildAsk.replaceAll("______________________","_");
        mWvAsk.loadData(SubChildAsk+"","text/html","utf-8");
    }

    /*
    * 切换作文作答方式
    * */
    private void changeZwAnswerType(){

        //键盘输入View
        mSBtnManualInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerViewFlag = 0;
                mSBtnManualInput.setSelected(true);
                mSBtnSpeechInput.setSelected(false);
                mSBtnPhotosUpload.setSelected(false);

                mLlViewManualInput.setVisibility(View.VISIBLE);
                mLlViewSpeechInput.setVisibility(View.GONE);
                mLlViewPhotosUpload.setVisibility(View.GONE);

            }
        });
        //语音输入View
        mSBtnSpeechInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerViewFlag = 1;
                mSBtnManualInput.setSelected(false);
                mSBtnSpeechInput.setSelected(true);
                mSBtnPhotosUpload.setSelected(false);

                mLlViewManualInput.setVisibility(View.GONE);
                mLlViewSpeechInput.setVisibility(View.VISIBLE);
                mLlViewPhotosUpload.setVisibility(View.GONE);


            }
        });
        //照片上传View
        mSBtnPhotosUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                answerViewFlag = 2;
                mSBtnManualInput.setSelected(false);
                mSBtnSpeechInput.setSelected(false);
                mSBtnPhotosUpload.setSelected(true);

                mLlViewManualInput.setVisibility(View.GONE);
                mLlViewSpeechInput.setVisibility(View.GONE);
                mLlViewPhotosUpload.setVisibility(View.VISIBLE);


            }
        });
    }

    private RecyclerView mRvMyPhotoPicker;
    private int themeId;
    private int chooseMode;
    private PhotoPickerAdapter adapter;
    public static List<LocalMedia> SelectList = new ArrayList<>();
    private int maxSelectNum = 9;
    private void showPhotosUploadView(View view){
        mRvMyPhotoPicker =  view.findViewById(R.id.rv_photoPicker);
//        mRvMyPhotoPicker.setLayoutManager(new GridLayoutManager(getActivity(), 3));
//        mRvMyPhotoPicker.setHasFixedSize(true);
//        mRvMyPhotoPicker.setAdapter(adapter);

        themeId = R.style.picture_default_style;
        chooseMode = PictureMimeType.ofAll();
        FullyGridLayoutManager manager = new FullyGridLayoutManager(getActivity(), 3,
                GridLayoutManager.VERTICAL, false);
        mRvMyPhotoPicker.setLayoutManager(manager);
        adapter = new PhotoPickerAdapter(getActivity(), onAddPicClickListener);
        adapter.setList(SelectList);
        adapter.setSelectMax(maxSelectNum);
        adapter.setOnItemClickListener(new PhotoPickerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (SelectList.size() > 0) {
                    LocalMedia media = SelectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            Log.e("==跳转==","=================进入图片选择器====================");
                            // 预览图片
                            PictureSelector.create(BkfxZwFragment.this).themeStyle(themeId).openExternalPreview(position, SelectList);
                            break;
                    }
                }
            }
        });
        mRvMyPhotoPicker.setAdapter(adapter);
    }

    private PhotoPickerAdapter.onAddPicClickListener onAddPicClickListener = new PhotoPickerAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            List<String> names = new ArrayList<>();
            names.add("拍照");
            names.add("相册");
            showDialog(new SelectDialog.SelectDialogListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    switch (position) {
                        case 0: // 直接调起相机
                            BkfxActivity.isNeedShowViewExit = false;
                            Log.e("==跳转==","=================进入相机====================");
                            PictureSelector.create(BkfxZwFragment.this)
                                    .openCamera(chooseMode)// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                                    .theme(themeId)// 主题样式设置 具体参考 values/styles
                                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                                    .minSelectNum(1)// 最小选择数量
                                    .imageSpanCount(3)// 每行显示个数
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选
                                    .previewImage(true)// 是否可预览图片
                                    .previewVideo(true)// 是否可预览视频
                                    .enablePreviewAudio(true) // 是否可播放音频
                                    .isCamera(true)// 是否显示拍照按钮
                                    .enableCrop(false)// 是否裁剪
                                    .compress(false)// 是否压缩
                                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                                    .isGif(true)// 是否显示gif图片
                                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                                    .circleDimmedLayer(false)// 是否圆形裁剪
                                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                                    .openClickSound(false)// 是否开启点击声音
                                    .selectionMedia(SelectList)// 是否传入已选图片
                                    .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

                            break;
                        case 1:
                            BkfxActivity.isNeedShowViewExit = false;
                            Log.e("==跳转==","=================进入相册====================");
                            // 进入相册 以下是例子：不需要的api可以不写
                            PictureSelector.create(BkfxZwFragment.this)
                                    .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                                    .minSelectNum(1)// 最小选择数量
                                    .imageSpanCount(3)// 每行显示个数
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                                    .previewImage(true)// 是否可预览图片
                                    .previewVideo(true)// 是否可预览视频
                                    .enablePreviewAudio(true) // 是否可播放音频
                                    .isCamera(true)// 是否显示拍照按钮
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                    .enableCrop(false)// 是否裁剪
                                    .compress(false)// 是否压缩
                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                                    .isGif(true)// 是否显示gif图片
                                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                    .circleDimmedLayer(false)// 是否圆形裁剪
                                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                                    .openClickSound(false)// 是否开启点击声音
                                    .selectionMedia(SelectList)// 是否传入已选图片
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                            break;
                        default:
                            break;
                    }
                }
            }, names);
        }
    };

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(getActivity(), R.style.transparentFrameWindowStyle, listener, names);
        dialog.show();
        return dialog;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    BkfxActivity.isNeedShowViewExit = true;
                    Log.e("==AAASSS==","=============photoFragment=========111111======");
                    // 图片选择
                    SelectList = PictureSelector.obtainMultipleResult(data);
                    adapter.setList(SelectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    public interface CallBackFragmentZw {
        void pageMoveNext();
        void saveBkfx_ZwQuesAnswer();
    }


    /********************************************************/
    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
//            Log.e("==onRecordingAA==","========vad_status==========="+"121212121212");
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
            Log.e("==onRecordingAA==","========vad_status==========="+vad_status);
            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            showRecordVolumeSize(sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(getActivity()).stopRecord();
                mRecoderUtils.stopRecord();
            }
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String speakResult = "";
                if(!getResult(result).equals("")) {
                    speakResult = getResult(result);
                }
                Log.e("==AFGAFGG==","========VVVVVVKKKKK》》==========="+speakResult);
                if(!speakResult.equals("")) {
//                    String stuAnswer = bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().get(0).getSubChildList().get(0).
//                            getSubChildItem().get(0).getStuAnswer();
//
//                    bkfxPaperEntity.getPaperAnswer().get(childIndex).getChildList().get(0).getSubChildList().get(0).
//                            getSubChildItem().get(0).setStuAnswer(stuAnswer+speakResult+".");
                    SpeechInputStuAnswer = SpeechInputStuAnswer+speakResult+".";
                    mCEdtSpeechInput.setText(SpeechInputStuAnswer);

                    SkEgnManager.getInstance(getActivity()).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                    mRecoderUtils.startRecord();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }
    /************************************************************/
    private PopupWindow popWindow;
    private ImageView mIvRecordVolume;
    private Drawable drawableVolume;
    private void showRecordPopwindow(Button btnPop) {

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popuw_content_top_arrow_layout, null);
        popWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);// 尽量写成数值，要不然左右弹出的位置不好控制
        popWindow.setAnimationStyle(R.style.MyDialogScale);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);

        mIvRecordVolume = contentView.findViewById(R.id.iv_RecordVolume);
        drawableVolume = mIvRecordVolume.getDrawable();

        int popupWidth = popWindow.getWidth();
        int popupHeight = popWindow.getHeight();
        int width = btnPop.getWidth();
        int height = btnPop.getHeight();
        popWindow.showAsDropDown(btnPop, 0, 30-(popupHeight+2*height));
//        popWindow.showAsDropDown(btnPop, (width - popupWidth) / 2, 0);
    }

    private void showRecordVolumeSize(final int volumesize){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg =Message.obtain();
                msg.obj = volumesize;
                msg.what = 1;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int VolumeSize = Integer.valueOf(msg.obj.toString());
                    if(VolumeSize>50){
                        VolumeSize=50;
                    }
                    int LevelSize = VolumeSize*200;
                    drawableVolume.setLevel(LevelSize);
                    break;
            }
        }
    };


    public static List<String> getFilesAllName(String path) {
        File file=new File(path);
        File[] files=file.listFiles();
        if (files == null){Log.e("error","空目录");return null;}
        List<String> s = new ArrayList<>();
        for(int i =0;i<files.length;i++){
            s.add(files[i].getAbsolutePath());
        }
        return s;
    }

    /**

     * 需求:将两个amr格式音频文件合并为1个

     * 注意:amr格式的头文件为6个字节的长度

     * @param partsPaths       各部分路径

     * @param unitedFilePath   合并后路径

     */

    public void uniteAMRFile(String[] partsPaths, String unitedFilePath) {

        try {
            File unitedFile = new File(unitedFilePath);
            FileOutputStream fos = new FileOutputStream(unitedFile);
            RandomAccessFile ra = null;
            for (int i = 0; i < partsPaths.length; i++) {
                ra = new RandomAccessFile(partsPaths[i], "r");
                if (i != 0) {
                    ra.seek(6);
                }
                byte[] buffer = new byte[1024 * 8];
                int len = 0;
                while ((len = ra.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }
            ra.close();
            fos.close();
        } catch (Exception e) {

        }
    }

}
